import 'dart:async';
import 'dart:convert';
import 'dart:developer';

import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';
import 'package:ball_lion/service/third_login_service.dart';
import 'package:ball_lion/service/umeng_service.dart';
import 'package:ball_lion/entity/other/auth_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/server/api/user_api.dart';
import 'package:ball_lion/utils/constant.dart';
import 'package:ball_lion/utils/regex_util.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/sp_utils.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/module/mine/login_safety_view.dart';
import 'package:ball_lion/module/mine/my_web_page.dart';
import 'package:ball_lion/widgets/base/wqs_dialog.dart';
import 'package:tencent_kit/tencent_kit.dart';

enum LoginType { login, bind }

class LoginLogic extends GetxController {
  late final WeChatResponseSubscriber _wechatListener;
  late final StreamSubscription<TencentResp> _qqListener;
  // late final StreamSubscription<BaseResp> _wbListener;
  final agreePrivacy = false.obs;
  String? phoneNumber;
  Timer? _timer;
  final _currentTime = 60.obs;
  LoginType type = LoginType.login;
  final thirdLoginService = Get.find<ThirdLoginService>();

  AuthEntity? auth;

  int get currentTime => _currentTime.value;

  set currentTime(int value) {
    _currentTime.value = value;
    update();
  }

  @override
  void onInit() async {
    final data = Get.arguments;
    if (data != null) {
      type = data as LoginType;
    }
    try {
      //第一次三方登录绑定手机传参
      if (Get.parameters['auth'] != null) {
        String param = Get.parameters['auth'] as String;
        auth = AuthEntity.fromJson(jsonDecode(param));
      }
    } catch (e) {}
    _wechatListener = (response) {
      if (response is WeChatAuthResponse) {
        if (response.errCode == 0) {
          thirdLogin(wxCode: response.code);
        }
      }
    };
    Fluwx().addSubscriber(_wechatListener);
    _qqListener = TencentKitPlatform.instance.respStream().listen((event) {
      log('$event');
      if (event is TencentLoginResp) {
        TencentLoginResp auth = event;
        if (auth.ret == 0) {
          thirdLogin(qqAccessToken: auth.accessToken, qqOpenid: auth.openid);
        }
      }
    });
    // _wbListener = WeiboKitPlatform.instance.respStream().listen((event) {
    //   log('$event');
    //   if (event is AuthResp) {
    //     AuthResp auth = event;
    //     if (auth.errorCode == 0) {
    //       thirdLogin(wbAccessToken: auth.accessToken, wbUid: auth.userId);
    //     }
    //   }
    // });

    // await WechatKitPlatform.instance.handleInitialWXReq();

    // Get.find<UmengService>().login(type, userId: auth?.userId);
    super.onInit();
  }

  @override
  void onClose() {
    Fluwx().removeSubscriber(_wechatListener);
    _qqListener.cancel();
    //_wbListener.cancel();
    _timer?.cancel();
    super.onClose();
  }

  Future<bool> checkAgree() async {
    if (!agreePrivacy.value) {
      // Utils.alertQuery("请同意用户协议与隐私政策");
      bool back = await Get.dialog(QsDialog.alert(
        "服务协议及隐私保护",
        contentWidget: RichText(
            text: TextSpan(children: [
          TextSpan(children: [
            const TextSpan(text: '已阅读并同意', style: TextStyle(color: Colours.N7)),
            TextSpan(
                text: '《服务协议》',
                style: const TextStyle(color: Colours.main),
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    Get.toNamed(Routes.webview,
                        arguments: WebPara(Constant.serviceAgreementUrl,
                            title: "用户协议", longpress: true));
                  }),
            const TextSpan(text: '和', style: TextStyle(color: Colours.N7)),
            TextSpan(
                text: '《隐私政策》',
                style: const TextStyle(color: Colours.main),
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    Get.toNamed(Routes.webview,
                        arguments: WebPara(Constant.privacyPolicyUrl,
                            title: "隐私政策", longpress: true));
                  }),
            const TextSpan(
                text: '，平台将严格保护你的个人信息安全', style: TextStyle(color: Colours.N7)),
          ])
        ])),
        confirmText: "同意并登录",
        cancelText: "不同意",
        //buttonDirection: Axis.vertical,
      ));
      if (back == true) {
        agreeUserPrivacy();
      }
      // Toast.text('请同意用户协议与隐私政策');
    }
    return agreePrivacy.value;
  }

  agreeUserPrivacy() {
    Utils.onEvent('wode_dxdl_xy',
        params: {'wode_dxdl_xy': agreePrivacy.value ? '0' : '1'});
    agreePrivacy.value = !agreePrivacy.value;
  }

  void _startCount() {
    currentTime = 60;
    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (currentTime == 0) {
        _timer?.cancel();
      } else {
        currentTime--;
      }
    });
  }

  Future<bool> doSendSms(String phoneNum) async {
    if (!await checkAgree()) {
      return false;
    }
    // final phone = phoneController.text;
    final reg = RegExp(RegexUtil.phone);
    if (!reg.hasMatch(phoneNum)) {
      WidgetUtils.alertQuery("请输入正确的手机号");
      return false;
    }
    // final result = await UserApi.kaptchaImage('1234');
    // print(result);
    final safe = await Get.dialog(const LoginSafetyViewView());
    if (safe) {
      final result =
          await UserApi.sendSms(phoneNum, type == LoginType.login ? 1 : 2);
      if (result == 200) {
        phoneNumber = phoneNum;
        _startCount();
        return true;
        //Get.toNamed(Routes.myLoginVerify, arguments: type);
      }
    }
    return false;
  }

  resendSms() async {
    final result =
        await UserApi.sendSms(phoneNumber!, type == LoginType.login ? 1 : 2);
    if (result == 200) {
      _startCount();
    }
  }

  visitorLogin() async {
    if (!await checkAgree()) return;
    final result = await User.visitorLogin();
    if (result != null) Get.back();
  }

  doLogin(String code) async {
    if (!await checkAgree()) return;
    Utils.onEvent('wode_yjdl_dl');
    if (type == LoginType.bind) {
      final result = await UserApi.bindPhone(
          phone: phoneNumber!, smsCode: code, userId: auth?.userId);
      if (result != null) {
        SpUtils.loginAuth = result;
        await User.doLogRefresh(isLogin: true);
        update();
        // Get.find<UmengService>().completeLogin();
        Get.until((route) => Get.currentRoute == Routes.navigation);
      }
    } else {
      final result = await UserApi.login(phone: phoneNumber!, smsCode: code);
      if (result != null) {
        SpUtils.loginAuth = result;
        await User.doLogRefresh(isLogin: true);
        update();
        // Get.find<UmengService>().completeLogin();
        Get.back();
      }
    }
  }

  // appleLogin() async {
  //   if (!await checkAgree()) {
  //     return;
  //   }
  //   Utils.onEvent('wd_dl', params: {'wd_dl': '3'});
  //   final credential = await thirdLoginService.onAppleLogin();
  //   final result =
  //       await UserApi.thirdLogin(iosIdentityToken: credential.identityToken);
  //   if (result != null) {
  //     SpUtils.loginAuth = result;
  //     User.doLogRefresh(isLogin: true);
  //     Get.back();
  //   }
  // }

  thirdLogin(
      {String? qqAccessToken,
      String? qqOpenid,
      String? wbAccessToken,
      String? wbUid,
      String? iosIdentityToken,
      String? wxCode}) async {
    final result = await UserApi.thirdLogin(
        qqAccessToken: qqAccessToken,
        qqOpenid: qqOpenid,
        wbAccessToken: wbAccessToken,
        wbUid: wbUid,
        iosIdentityToken: iosIdentityToken,
        wxCode: wxCode);
    if (result != null) {
      if (result.phone!.startsWith('2')) {
        Get.toNamed(Routes.login,
            arguments: LoginType.bind,
            preventDuplicates: false,
            parameters: {'auth': jsonEncode(result.toJson())});
        // auth = result;
      } else {
        SpUtils.loginAuth = result;
        User.doLogRefresh(isLogin: true);
        Get.back();
      }
    }
  }

  onWechatLogin() async {
    if (!await checkAgree()) {
      return;
    }
    Utils.onEvent('wd_dl', params: {'wd_dl': '0'});
    thirdLoginService.onWechatLogin();
  }

  onQQLogin() async {
    if (!await checkAgree()) {
      return;
    }
    Utils.onEvent('wd_dl', params: {'wd_dl': '1'});
    thirdLoginService.onQQLogin();
  }

  // onWeiboLogin() async {
  //   if (!await checkAgree()) {
  //     return;
  //   }
  //   Utils.onEvent('wd_dl', params: {'wd_dl': '2'});
  //   thirdLoginService.onWeiboLogin();
  // }
}
